#  Copyright (c) 2021
#  User:SDUFE-Zhaocheng Lu
#  File:get_data.py
#  Date:2021/08/17 23:21:17
import requests, lib
from lxml import etree
import base64


def post_ERROR(error_id):
    requests.post('http://upload.chaojiying.net/Upload/ReportError.php', data={
        'user': 'DMSintalor',
        'pass': 'LzC200138',
        'softid': '914617',
        'id': error_id,
    })


class GetData:
    fin_data = {}

    def __init__(self, user_data, city_id) -> None:
        super().__init__()
        self.sess = requests.session()
        self.login_cnt, self.login_status = 0, 0
        self.user_data = user_data
        self.city_id = city_id

    def get_new_captcha(self):
        jpg = self.sess.get('http://bcfl.sdufe.edu.cn/index.php?g=api&m=checkcode&a=index&time=').content
        file = base64.b64encode(jpg)
        return file

    def get_captcha(self):
        file_base64 = self.get_new_captcha()
        url = 'http://upload.chaojiying.net/Upload/Processing.php'
        data = {
            'user': 'DMSintalor',
            'pass': 'LzC200138',
            'softid': '914617',
            'codetype': '4004',
            'len_min': 0,
            'file_base64': file_base64,
        }
        res = requests.post(url=url, data=data).json()
        return res['pic_str'], res['pic_id']

    def login_start(self):
        while self.login_cnt < lib.fail_times and not self.login_status == 200:
            verify_code, verify_id = self.get_captcha()
            login_res = self.sess.post(url='http://bcfl.sdufe.edu.cn/Student/handle_login', data={
                'number': self.user_data[0],
                'card': self.user_data[1],
                'verify': verify_code
            }).json()
            if login_res['code'] == 203:
                print('密码:\t错误!')
                self.login_status = login_res['code']
                return self.login_status
            if login_res['code'] == 201:
                post_ERROR(verify_id)
            self.login_status = login_res['code']
            self.login_cnt += 1
        return self.login_status

    def get_data(self):
        try:
            res = self.sess.get('http://bcfl.sdufe.edu.cn/student/handle_ext.html')
            doms = etree.HTML(res.text)
            qd_field = lib.data_field
            fin = {}
            for field in qd_field:
                if field == 'sex':
                    fin[field] = doms.xpath('//*[@name="sex" and @checked]/@value')[0]
                elif field == 'college_id':
                    fin[field] = doms.xpath('//*[@name="college_id"]//*[@selected]/@value')[0]
                elif field == 'province_id':
                    fin[field] = doms.xpath('//*[@name="province_id"]//*[@selected]/@value')[0]
                elif field == 'city_id':
                    fin[field] = self.city_id
                else:
                    fin[field] = doms.xpath('//*[@id="{}"]/@value'.format(field))[0]
            self.fin_data = fin
            return True
        except:
            return False

    def insert(self):
        SQL = lib.SQL()
        value_list = []
        values = ','.join(["\'" + data + "\'" for data in self.user_data])
        for item in self.fin_data.items():
            value_list.append(str(item[1]))
        values = values + ',' + ','.join(["\'" + data + "\'" for data in value_list])
        sql = "insert into userprofile ({}, addTime, expireTime) VALUES ({}, CURDATE(), ADDDATE(curdate(), 30))".format(
            ','.join(lib.field_name),
            values
        )
        try:
            SQL.run(sql)
            SQL.db.commit()
            print('执行成功\t%s已被插入表中' % self.user_data[0])
        except Exception as e:
            SQL.db.rollback()
            print('执行失败\t%s' % e)


Func = GetData(user_data=['20191874149', '313013', '872671010@qq.com'], city_id='170')
login_status = Func.login_start()
if login_status == 200:
    if Func.get_data():
        Func.insert()
